var oper = getQueryString('oper') //当前弹窗类型
var userId = getQueryString('id') //从列表传过来的用户id

$(function () {
  $.common.initFormInfo();

  if (oper === 'view') {
    $("#btnShow").remove();
  }

  //获取用户详情
  if (oper === 'edit' || oper === 'view') {
    getUserInfo(userId)
  }else{
    var result = {
      oper: oper,
      roleAll: JSON.parse(session.get('roleList'))
    }
    renderTpl('formTpl', result, 'formBox')
    tplInit()
    showIESwitch()
    validateForm()
  }


  jQuery.validator.addMethod("loginNameRepeat", function (value, element) {
    var result;
    $.ajax({
      url: api+'/admin/user/details/'+value,
      async: false,
      type: 'get',
      success: function (res) {
        result = !Boolean(res.data)
      }
    });
    return result
  },"登录名已存在");

  $.common.initFormInfo();

})

function validateForm(){
  $("#editForm").validate({
    onkeyup: false,
    rules: {
      username: {
        required: true
      },
      deptName: {
        required: true
      },
      phone: {
        required: true,
        isPhone: true,
      },
      email: {
        required: true,
        email: true,
      },
      loginname: {
        required: true,
        minlength: 2,
        loginNameRepeat: oper === 'add',
      },
      password: {
        minlength: 6
      },
      roleId: {
        required: true,
      }
    },
    messages: {
      username: {
        required: "请输入用户名",
      },
      deptName: {
        required: "请选择归属部门",
      },
      phone: {
        required: "请输入手机号码",
        isPhone: "请输入正确的手机号码",
        remote: "手机号码已经存在"
      },
      email: {
        required: "请输入邮箱",
        email: "请输入正确的邮箱",
        remote: "邮箱已经存在"
      },
      loginname: {
        required: "请输入登录名",
        minlength: "登录名不能小于2个字符",
        remote: "登录名已经存在"
      },
      password: {
        minlength: "密码不能小于6个字符"
      },
      roleId: {
        required: "请至少选择一个角色",
      }
    },
    focusCleanup: true
  });
}



function getUserInfo(id) {
  $.operate.get(
    api + '/admin/user/' + id,
    function (res) {
      res.data.roleAll = JSON.parse(session.get('roleList'))
      res.data.roleAll.forEach(function (item) {
        res.data.roleList.forEach(function(k){
          item.flag = k.roleId == item.roleId
        })
      })
      res.data.oper = oper
      var result = res.data
      renderTpl('formTpl', result, 'formBox')
      //模板渲染后重新初始化代码
      tplInit()
      showIESwitch()
      validateForm()
      $.common.initFormInfo();
      if (oper === 'view') {
        $("#toggle-switch").off('click')
      }
    }, false)
}

/* 用户管理-修改-选择部门树 */
function selectDeptTree() {
  var deptId = $.common.isEmpty($("#treeId").val()) ? "" : $("#treeId").val();
  var url = "/pages/sysadm/dept/tree?deptId=" + deptId;
  var options = {
    title: '选择部门',
    width: "380",
    url: url,
    callBack: doSubmit
  };
  $.modal.openOptions(options);
}

function doSubmit(index, layero) {
  var tree = layero.find("iframe")[0].contentWindow.$._tree;
//	if ($.tree.notAllowParents(tree)) {
  var body = layer.getChildFrame('body', index);
  $("#treeId").val(body.find('#treeId').val());
  $("#treeName").val(body.find('#treeName').val());
  layer.close(index);
//	}
}

function submitHandler() {
  if ($.validate.form()) {
    var status;
    if (isIE8) {
      status = $("#toggle-switch").data('checked') == true ? 0 : 9;
    } else {
      status = $("input[id='status']").is(':checked') == true ? 0 : 9;
    }

    $('#lockFlag').val(status);
    var roleIds = $.form.selectCheckeds("roleId");
    var newPassword = $('#password').val();
    var data = {
      role: roleIds.split(','),
      password: newPassword ? algorithmRequestParam(newPassword) : ''
    }
    // $('#password').val(algorithmRequestParam(newPassword));
    $.common.ajaxCommitForm($('#editForm'), true, data);
    return false;
  }
}

function showIESwitch() {
  //ie8 用户状态开关按钮
  if (isIE8) {
    $("#toggle-switch").show()
    $("#toggle-switch-normal").hide()
    var firstCheckedFlag = $("#toggle-switch").data('checked')
    if (firstCheckedFlag) {
      $("#toggle-switch").addClass('fa-toggle-on').removeClass('fa-toggle-off')
    } else {
      $("#toggle-switch").addClass('fa-toggle-off').removeClass('fa-toggle-on')
    }

    $("#toggle-switch").click(function () {
      var checkedFlag = $(this).data('checked')
      $(this).data('checked', !checkedFlag)
      if ($(this).hasClass('fa-toggle-off')) {
        $(this).addClass('fa-toggle-on').removeClass('fa-toggle-off')
      } else {
        $(this).addClass('fa-toggle-off').removeClass('fa-toggle-on')
      }
    })
  } else {
    $("#toggle-switch").hide()
    $("#toggle-switch-normal").show()
  }
}